package com.fingard.dsp.bank.dbobj.secretkey;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.dbobj.unique.UniqueIdHelper;
import com.fingard.dsp.bank.helpers.dbhelpers.InsertHelper;
import com.fingard.dsp.bank.helpers.dbhelpers.LoadHelper;

import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.*;

/**
 * Created by F on 2020/3/30.
 */
public class SecretKeyDataHelper {

    private Connection partDbconn = null;
    private String tenant = "";

    /**！！注意：需在finally里显示调用close()方法
     * @param pTenant
     * @param pPartDate
     * */
    public SecretKeyDataHelper(String pTenant, Date pPartDate) throws Exception{
        tenant = pTenant;
        partDbconn = FGBiz.partTable.getLoaclDbConnByPart(pTenant, pPartDate);
    }

    /**
     * 获取租户
     * @return
     */
    public String getTenant(){
        return tenant;
    }

    private Connection localConn = null;

    private Connection getLocalDbConn() throws Exception{
        if(localConn == null){
            localConn = FGBiz.getLocalDbConn();
        }
        return localConn;
    }

    /**将密钥数据数据写入数据库表*/
    public int insertIfNotExist(SecretKeyData pData) throws Exception{
        return insertIfNoExistByIndex(pData, false);
    }

    /**
     * 根据索引(租户和日期)判断数据是否需要插入
     * @param pData 密钥数据
     * @param pRetZeroIfExist
     * @return 返回1代表插入成功，返回0代表已插入
     */
    public int  insertIfNoExistByIndex(SecretKeyData pData ,boolean pRetZeroIfExist) throws Exception{
        Object[] objs = new Object[2];
        objs[0] =pData.tenant;
        objs[1] = pData.busDate;
        String chkSql = "select count(*) from SECRETKEY where TENANT =? and BUSDATE =?";
        Object chkObj = JDBCHelper.execScalar(partDbconn, chkSql, objs);
        int chkCount = -1;
        if(chkObj != null){
            chkCount = Integer.parseInt(chkObj.toString());
        }
        if(chkCount <= 0){
            pData.urid = UniqueIdHelper.getUniqueId(getLocalDbConn(), "SECRETKEY");
            pData.createdOn = new Date();
            pData.lastModifiedOn = new Date();
            pData.rowVersion = 1;
            int rowAff = InsertHelper.insertObject(partDbconn, "SECRETKEY", pData);
            if(rowAff == 1){
                return 1;
            }else{
                throw new Exception("写入SECRETKEY的影响行数："+rowAff);
            }
        }else{
            if(pRetZeroIfExist){
                return 0;
            }
            return chkCount;
        }
    }

    /**
     * 获取对称密钥
     * @param pDate 时间
     * @return
     * @throws SQLException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws ParseException
     */
    public ArrayList<SecretKeyData> getSecretKeyDataList( Date pDate) throws SQLException, IllegalArgumentException, IllegalAccessException, ParseException{

        int busDate = Integer.parseInt(Format.Date8Format.format(pDate));
        String sql = "select * from SECRETKEY where TENANT=? and BUSDATE=?";
        Object[] objs = new Object[2];
        objs[0] = tenant;
        objs[1] = busDate;
        List<Map<String, Object>> mapList = JDBCHelper.execQuery(partDbconn, sql, objs);
        ArrayList<SecretKeyData> retList = new ArrayList<SecretKeyData>();
        if (mapList != null && mapList.size() > 0) {
            for (int i = 0; i < mapList.size(); i++) {
                Map<String, Object> eachMap = mapList.get(i);
                SecretKeyData eachData = new SecretKeyData();
                LoadHelper.loadObject(eachMap, eachData);
                retList.add(eachData);
            }
        }
        return retList;
    }


    public String getKey( Date pDate)throws Exception{
        ArrayList<SecretKeyData> retList= getSecretKeyDataList(pDate);
       if(retList==null||retList.size()==0){
           String ex =String.format("租户【%s】在日期【%s】没有对应的对称密钥",tenant,Format.Date8Format.format(pDate));
           throw new Exception(ex);
       }else if(retList.size()==1){
            return retList.get(0).key;
       }else {
           String ex =String.format("租户【%s】在日期【%s】的对称密钥有【%s】份!",tenant,Format.Date8Format.format(pDate),retList.size());
           throw new Exception(ex);
       }
    }


    /**
     * 获取一个有效的密钥，没有就创建
     * @param pDate
     * @return
     */
    public String createEffectiveKey(Date pDate)throws Exception{
        ArrayList<SecretKeyData> keyList =  getSecretKeyDataList(pDate);
        if(keyList==null||keyList.size()==0){
            SecretKeyData data = new SecretKeyData();
            data.busDate = Integer.valueOf(Format.Date8Format.format(pDate));
            data.tenant  = tenant;
            data.key = data.tenant+"-"+data.busDate+"-"+ new Random().nextInt(100);
            int resutl =insertIfNoExistByIndex(data,false);
            if(resutl==1){
                return data.key;
            }else{
                throw new Exception("插入异常");
            }
        }else if(keyList.size()==1){
            return keyList.get(0).key;
        } else{
            String exMsg =String.format("客户【%s】在日期【%s】的密钥个数有【%s】个!",tenant,Format.Date8Format.format(pDate),keyList.size());
            throw new Exception(exMsg);
        }
    }





}
